var express = require('express');
var session = require('express-session');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var config = require('./config');
var log = require('./core/logger').getLogger("system");
var app = express();

app.loadConfig = function(key, val) {
    var env = this.get('env');
    val = require(val);
    if (val[env]) {
        val = val[env];
    }
    this.set(key, val);
};
app.loadConfig('mysql', path.join(config.root, '/config/mysql.json'));

// 使用 session 中间件
app.use(session({
    secret :  'secret', // 对session id 相关的cookie 进行签名
    resave : true,
    saveUninitialized: false, // 是否保存未初始化的会话
    cookie : {
        maxAge : 60 * 60 * 1000, // 设置 session 的有效时间，单位毫秒
    },
}));

var sequlize_pool = require(path.join(config.root, '/core/sequlize_pool')).init(app);
app.set('sequlize_pool', sequlize_pool);

app.use(bodyParser.json({limit: '50mb'})); // 限制上传5M
app.use(bodyParser.urlencoded({ extended: false , limit: '50mb' }));

// view engine setup
app.set('views', path.join(config.root, '/app/views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
// app.use(favicon(config.root + '/public/favicon.ico'));
app.use(logger('dev'));

app.use(function (req, res, next) {
    var data = '';
    req.setEncoding('utf8');
    req.on('data', function (chunk) {
        data += chunk;
    });
    req.on('end', function () {
        req.rawBody = data;
    });
    if (isLogin(req)) {
        return res.redirect("/login");
    }
    // if (!checkAuth(req)) {
    //     res.status(401);
    //     res.render('401', {
    //         message: "没有权限访问该页面",
    //         error: {}
    //     });
    //     return;
    // }
    next();
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(config.root, 'public')));

// load all models
require(path.join(config.root, 'app/models'));

// load all controllers
app.use(require(path.join(config.root, '/app/controllers')));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
if (app.get('env') === 'production') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });
}

var isLogin = function (req) {
    if (req.session.user){
        return false;
    }

    var arr = req.url.split('/');
    for (var i = 0, length = arr.length; i < length; i++) {
        arr[i] = arr[i].split('?')[0];
    }
    if (arr.length < 2){
        return false;
    }

    var array = ['css','fonts','img','js','plugins','service','login','logout','verify','401','error'];
    if (isInArray(array, arr[1])){
        return false;
    }

    return true;
};

var isInArray = function (arr,value){
    for(var i = 0; i < arr.length; i++){
        if(value === arr[i]){
            return true;
        }
    }
    return false;
};

var checkAuth = function (req) {
    var url = req.url;
    var urls = url.split("/");
    var cname = urls.length > 0 ? "/" + urls[1] : "/";
    var menu_roles = req.session.menu_roles;
    var exists = false;
    var array = ['','css','fonts','img','js','plugins','service','login','logout','verify','401','error'];
    if (isInArray(array, urls[1])){
        exists = true;
    } else {
        for (var i = 0; i < menu_roles.length; i++) {
            var menu_role = menu_roles[i];
            var menu_url = menu_role['menu_url'];
            if(menu_url == "/") {
                continue;
            }
            if (menu_url != "" && cname == menu_url) {
                exists = true;
                break;
            }
        }
    }
    return exists;
};

module.exports = app;
